package com.jkoss.wine.shopOrder.controller;

import java.text.ParseException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jkoss.base.controller.BaseController;
import com.jkoss.common.util.CommonUtil;
import com.jkoss.common.vo.DwzPageBean;
import com.jkoss.wine.config.mvc.MoneyExcelHandler;
import com.jkoss.wine.merchantOrder.vo.MerchantOrderVo;
import com.jkoss.wine.shop.entity.Shop;
import com.jkoss.wine.shop.service.IShopService;
import com.jkoss.wine.shopOrder.entity.Orders;
import com.jkoss.wine.shopOrder.service.IOrdersService;
import com.jkoss.wine.shopOrder.vo.OrdersVo;
import com.jkoss.wine.system.entity.Role;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.handler.inter.IExcelDataHandler;

/**
 * 前端控制器
 * 
 * @Author Jason
 * @Version 1.0, 2018-10-14
 * @See
 * @Since com.jkoss.wine.shopOrder.controller
 * @Description: TODO
 */
@Controller
@RequestMapping("/shopOrder/orders")
public class OrdersController extends BaseController {

	@Autowired
	private IOrdersService iOrdersService;

	@Autowired
	private IShopService iShopService;

	/**
	 * 列表
	 * 
	 * @param orderNum
	 * @param shopName
	 * @param startTime
	 * @param endTime
	 * @param dwzPageBean
	 * @param map
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/list")
	@RequiresPermissions("/shopOrder/orders/list")
	public String list(String orderNum, String shopName, String startTime, String endTime, DwzPageBean dwzPageBean, ModelMap map, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String string1 = request.getParameter("org2.orderNum");
		String string2 = request.getParameter("org2.shopName");
		dwzPageBean.getCountResultMap().put("orderNum", string1);
		dwzPageBean.getCountResultMap().put("shopName", string2);
		dwzPageBean.getCountResultMap().put("startTime", startTime);
		dwzPageBean.getCountResultMap().put("endTime", endTime);
		Wrapper wrapper = Condition.create().ne("a.del", 1).eq("a.order_type", 1).like("a.order_num", string1).like("s.shop_name", string2);
		boolean isDirector = true;
		List<Role> roles = getRoleList();
		for (Role role : roles) {
			if ("运营主管".equals(role.getName())) {
				isDirector = false;
			}
		}
		if (isDirector) {
			// s.maid跟进人id，也就是总店员工id，(只能查看自己跟进的客户)，如果此处为false就不根据maid来查，即查询全部
			wrapper.eq("s.maid", getUserId());
		}
		if (!CommonUtil.isBlank(startTime)) {
			// 大于等于开始时间
			wrapper.ge("a.add_time", startTime);
		}
		if (!CommonUtil.isBlank(endTime)) {
			// 小于等于结束时间
			wrapper.le("a.add_time", CommonUtil.dateLastTime(endTime));
		}

		// 字段排序
		if (!CommonUtil.isBlank(dwzPageBean.getOrderField()) && !CommonUtil.isBlank(dwzPageBean.getOrderDirection())) {
			dwzPageBean.getCountResultMap().put("orderField", dwzPageBean.getOrderField());
			dwzPageBean.getCountResultMap().put("orderDirection", dwzPageBean.getOrderDirection());
			wrapper.orderBy(dwzPageBean.getOrderField(), CommonUtil.isEquals(dwzPageBean.getOrderDirection(), "asc"));
		} else {
			wrapper.orderBy("a.add_time", false);
		}

		Page resultPage = iOrdersService.selectVoByPage(dwzPageBean.toPage(), wrapper);
		map.put("dwzPageBean", dwzPageBean.toDwzPageBean(resultPage));
		return "shopOrder/orders/list";
	}

	/**
	 * 去新增
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/toInsert")
	@RequiresPermissions("/shopOrder/orders/toInsert")
	public String toInsert(HttpServletRequest request, HttpServletResponse response) {
		return "shopOrder/orders/edit";
	}

	@RequestMapping("/insert")
	@RequiresPermissions("/shopOrder/orders/toInsert")
	@ResponseBody
	public Object insert(@Valid Orders orders, HttpServletRequest request, HttpServletResponse response) {
		if (iOrdersService.insert(orders)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}

	}

	/**
	 * 去修改
	 * 
	 * @param id
	 * @param map
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/toUpdate")
	@RequiresPermissions("/shopOrder/orders/toUpdate")
	public String toUpdate(String id, ModelMap map, HttpServletRequest request, HttpServletResponse response) {
		map.put("record", iOrdersService.selectById(id));
		return "shopOrder/orders/edit";
	}

	@RequestMapping("/update")
	@RequiresPermissions("/shopOrder/orders/toUpdate")
	@ResponseBody
	public Object update(@Valid Orders orders, HttpServletRequest request, HttpServletResponse response) {
		if (iOrdersService.updateById(orders)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}
	}

	/**
	 * 去删除
	 * 
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("/shopOrder/orders/delete")
	@ResponseBody
	public Object delete(String[] id, HttpServletRequest request, HttpServletResponse response) {
		if (iOrdersService.deleteBatchIds(Arrays.asList(id))) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}
	}

	/**
	 * 查询订单编号
	 * 
	 * @param orderNum
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping("/getOrderNum")
	@ResponseBody
	public Object getOrderNum(String orderNum, HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		Wrapper wrapper = Condition.create().like("order_num", orderNum).ne("del", 1);
		List<Shop> list = iOrdersService.selectList(wrapper);
		return JSON.toJSONString(list);
	}

	/**
	 * 查询店铺名称
	 * 
	 * @param shopName
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping("/getShopName")
	@ResponseBody
	public Object getShopName(String shopName, HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		Wrapper wrapper = Condition.create().like("shop_name", shopName).ne("del", 1);
		List<Shop> list = iShopService.selectList(wrapper);
		return JSON.toJSONString(list);
	}

	/**
	 * 导出Excel
	 * 
	 * @param map
	 * @param dwzPageBean
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/export")
	@RequiresPermissions("/shopOrder/orders/export")
	public String export(ModelMap map, DwzPageBean dwzPageBean, HttpServletRequest request, HttpServletResponse response) {
		// 从数据库中查找数据
		Wrapper wrapper = Condition.create().ne("a.del", 1).ne("a.order_type", 0);
		// 根据用户id获取角色
		boolean isDirector = true;
		List<Role> roles = getRoleList();
		for (Role role : roles) {
			if ("运营主管".equals(role.getName())) {
				isDirector = false;
			}
		}
		if (isDirector) {
			wrapper.eq("maid", getUserId());
		}
		Page page = dwzPageBean.toPage();
		page.setSize(Page.NO_ROW_LIMIT);
		page.setCurrent(1);
		List list = iOrdersService.selectVoByPage(page, wrapper).getRecords();
		ExportParams params = new ExportParams(null, "订单列表", ExcelType.XSSF);
		IExcelDataHandler dataHandler = new MoneyExcelHandler();
		dataHandler.setNeedHandlerFields(new String[] { "订单金额", "实收金额", "活动优惠金额" });
		params.setDataHandler(dataHandler);
		map.put(NormalExcelConstants.DATA_LIST, list); // 数据集合
		map.put(NormalExcelConstants.CLASS, OrdersVo.class);// 导出实体
		map.put(NormalExcelConstants.PARAMS, params);// 参数
		map.put(NormalExcelConstants.FILE_NAME, "订单列表");// 文件名称
		return NormalExcelConstants.EASYPOI_EXCEL_VIEW;// View名称
	}

}
